import { useEffect, useState, useRef } from 'react';

export default function({ domain, postMsg }: { domain: String; postMsg: Function }) {
  const iframeRef = useRef<any>(null);

  const sentMeg = (data: any) => {
    if (iframeRef.current && iframeRef.current.contentWindow) {
      iframeRef.current.contentWindow.postMessage(data, domain);
    }
  };

  useEffect(() => {
    const _postmessage = function(event: any) {
      try {
        //  if (!_this.$refs.cubeDecorate) return window.removeEventListener('message', _postmessage);
        const data = event.data || {};
        // 数据规范 code, data
        if (data.code && data.data) {
          console.log('data', data);
          const _data = data.data;
          if (_data.x > 0 && _data.y > 0) {
            //    console.log("data", _data);
          }
          if (data.code == 'config') {
            console.log(data);
          }
          if (data.code == 'mousemove') {
            //     handleMousemove(data.data);
          }
          if (data.code == 'moveholddom') {
            //  _this.isPlaceholder = false;
          }
          if (data.code == 'edit') {
            // 编辑
            //   _this.editCallBack(data);
          }
          postMsg(data);
        }
      } catch (e) {
        console.error('webview message', e);
      }
    };
    window.addEventListener('message', _postmessage, false);
  }, []);

  return { sentMeg, iframeRef };
}
